<?php
require_once('TVB/pms/pdes/common/util/mis/MisCommon.class.php');
require_once 'TVB/pms/pdes/common/util/mis/MisMapping.class.php';
require_once 'TVB/pms/pdes/CmsFramework/form_helper.php';

class MisLogGetAction extends BaseAction
{
    public $act;
    public $id;
    public $pdes_type;
	public $update;
	public $table;
    public $ut;

    public function execute()
    {
		$mis_log = new mis_log;
		$mis_log_detail = $mis_log->get(array($this->id, $this->pdes_type));

        if (empty($mis_log_detail)) return 'system-error';

		if ($this->update) {
			$rs = $this->updateByMis($mis_log_detail);
			return $rs ? 'succ_update' : 'system-error';
		}

		switch ($this->act) {
			case 'view':
				$rs = $this->showDetail((array) $mis_log_detail);
				return $rs ? 'succ_view' : 'system-error';
				break;
			case 'recover':
				$rs = $this->recover($mis_log_detail);
				return $rs ? 'succ_recover' : 'filter-error';
				break;
		}
    }

    public function showDetail(array $mis_log) 
    {
        $ret = array();
		$old_modified_at = '2010-11-20 00:00:00';

        $sync_data = json_decode($mis_log['sync_data'], TRUE);
        $mis_data = json_decode($mis_log['mis_data'], TRUE); 
		$recover_data = json_decode($mis_log['recover_data'], TRUE);
		$flag_new = ($mis_log['modified_at'] > $old_modified_at) ? TRUE : FALSE;

        foreach ($mis_data as $table_name=>$row) {
			$lang = preg_match('/(zh|en)$/', $table_name, $matches) ? $matches[0] : '';
			$ui_list = MisMapping::getUiName(str_replace(' ', '-', preg_replace('/[-|_]language_(zh|en)$/', '-language', strtolower($table_name))), $lang);

			switch ($table_name) {
				case 'Info_Award':
					$this->__formatInfoAwardUiData($recover_data[$table_name]);
					break;
				case 'Info_Recipe':
					$this->__formatInfoRecipeUiData($recover_data[$table_name]);
					break;
				case 'Info_Song':
					$this->__formatInfoSongUiData($recover_data[$table_name]);
					break;
			}

			$programme_id = 88;

            foreach ($row as $field=>$new_value) {
				if ($table_name == 'programme' && ($field == 'cpl_category_id' || $field == 'first_time_onair')) {
					continue;
				}

				if ((strtolower($table_name) == 'programme' || strtolower($table_name) == 'episode') && $field == 'casts') {
					$arr = array(
						'ui_name' => $flag_new ? (empty($ui_list[$field]) ? '' : $ui_list[$field]) : $field, 
						'new_value' => is_array(json_decode($new_value, true)) ? $this->showCasts(json_decode($new_value, true)) : $new_value,
						'old_value' => empty($sync_data[$table_name][$field]) ? '' : (is_array(json_decode($sync_data[$table_name][$field], true)) ? $this->showCasts(json_decode($sync_data[$table_name][$field], true)) : $sync_data[$table_name][$field]), 
					); 

					if ($flag_new) {
						$arr['field1'] = '<input type="checkbox" name="table[' . $table_name .'][]" value="' . $field . '"  />';
						$arr['recover_value'] = empty($recover_data[$table_name][$field]) ? '' : (is_array(json_decode($recover_data[$table_name][$field], true)) ? $this->showCasts(json_decode($recover_data[$table_name][$field], true)) : $recover_data[$table_name][$field]);
					}
				} else {
					$arr = array(
						'ui_name' => $flag_new ? (empty($ui_list[$field]) ? '' : $ui_list[$field]) : $field, 
						'new_value' => $new_value,
						'old_value' => empty($sync_data[$table_name][$field]) ? '' : $sync_data[$table_name][$field], 
					); 

					if ($flag_new) {
						$arr['field1'] = '<input type="checkbox" name="table[' . $table_name .'][]" value="' . $field . '"  />';
						$arr['recover_value'] = empty($recover_data[$table_name][$field]) ? '' : $recover_data[$table_name][$field];
					}
				}

				$ret[$table_name][] = $arr;
			}
        }

        $this->setData('pdes_type', $this->pdes_type);
        $this->setData('id', $this->id);
        $this->setData('sync', $ret);
		$this->setData('flag_new', $flag_new);

        return TRUE;
    }

    public function recover($mis_log_detail)
    {
		try {
			Model::$dbo['w']->beginTransaction();
			$this->__recover($mis_log_detail->recover_data, $mis_log_detail->pdes_id);
			Model::$dbo['w']->commit();
		} catch (Exception $e) {
			error_log('MIS recover failure:'.$e->getMessage());
			Model::$dbo['w']->rollback();
			return FALSE;
		}

        $this->setData('type', 'mis');
        return TRUE;
    }

	private function __recover($recover_data, $id)
	{
		$recover_data = json_decode($recover_data, TRUE);
		if (!is_array($recover_data) && empty($recover_data)) {
			return FALSE;
		}

		foreach ($recover_data as $table => $data) {
			$update_data = array();

			$lang = preg_match('/(zh|en)$/', $table, $matches) ? $matches[0] : '';
			switch ($lang) {
				case 'zh':
					$lang_id = language::getLanguageID(AC::LANGUAGE_ZH);
					break;
				case 'en':
					$lang_id = language::getLanguageID(AC::LANGUAGE_EN);
					break;
				default:
					break;
			}

			$table_name = str_replace(' ', '-', preg_replace('/[-|_]language_(zh|en)$/', '-language', strtolower($table)));
			$sql = 'UPDATE `' . $table_name . '` SET ';
			foreach ($data as $key => $value) {
				$sql .= '`'. $key . '`=:' . $key . ',';
				$update_data[':' . $key] = $value;
			}
			$sql = rtrim($sql, ','); 

			switch ($table) {
				case 'programme-language_zh':
				case 'programme-language_en':
					$sql .= ' WHERE programme_id = :id AND language_id = :language_id';
					$update_data[':id'] = $id;
					$update_data[':language_id'] = $lang_id;
					break;
				case 'Episode_language_zh':
				case 'Episode_language_en':
					$sql .= ' WHERE episode_id = :id AND language_id = :language_id';
					$update_data[':id'] = $id;
					$update_data[':language_id'] = $lang_id;
					break;
				case 'Cast Language':
					$sql .= ' WHERE cast_id = :id AND language_id = :language_id';
					$update_data[':id'] = $id;
					$update_data[':language_id'] = $lang_id;
					break;
				default:
					$sql .= ' WHERE id = :id';
					$update_data[':id'] = $id;
					break;
			}

			Model::updateBySql($sql, $update_data);
		}
	}

	public function updateByMis($mis_log_detail)
	{
		try {
			Model::$dbo['w']->beginTransaction();

			foreach ($this->table as $table_name => $fields) {
				$new_data = $this->__getUpateData($mis_log_detail, $table_name, $fields);
				switch ($table_name) {
					case 'programme':
						$this->__updateProgramme($this->id, $new_data);
						break;
					case 'programme-language_zh':
						$this->__updateProgrammeLanguage($this->id, $new_data, 'zh');
						break;
					case 'programme-language_en':
						$this->__updateProgrammeLanguage($this->id, $new_data, 'en');
						break;
					case 'Episode':
						$this->__updateEpisode($this->id, $new_data, $table_name);
						break;
					case 'Episode_language_zh':
						$this->__updateEpisodeLanguage($this->id, $new_data, $table_name, 'zh');
						break;
					case 'Episode_language_en':
						$this->__updateEpisodeLanguage($this->id, $new_data, $table_name, 'en');
						break;
					case 'Cast':
						$this->__updateCast($this->id, $new_data);
						break;
					case 'Cast Language':
						$this->__updateCastLanguage($this->id, $new_data);
						break;
					case 'Info_Award':
						$this->__formatInfoAwardData($new_data);
						$this->__updateInfo($this->id, $new_data, $table_name);
						break;
					case 'Info_Recipe':
						$this->__formatInfoRecipeData($new_data);
						$this->__updateInfo($this->id, $new_data, $table_name);
						break;
					case 'Info_Song':
						$this->__formatInfoSongData($new_data);
						$this->__updateInfo($this->id, $new_data, $table_name);
						break;
					case 'Info_Address':
					case 'Info_Biography':
					case 'info_general_information':
					case 'info_pageant':
					case 'info_product':
					case 'info_q_a':
						$this->__updateInfo($this->id, $new_data, $table_name);
						break;
				}
			}

			$mis_log_detail->recover_data = json_encode(MisCommon::$recover_data);
			$mis_log_detail->update($mis_log_detail);

			Model::$dbo['w']->commit();
		} catch (Exception $e) {
			Model::$dbo['w']->rollback();
			return FALSE; 
		}

        $this->setData('type', 'mis');
        $this->setData('pdes_type', $this->pdes_type);
        $this->setData('id', $this->id);
		return TRUE;
	}

	private function __getUpateData($mis_log_detail, $table, $fields)
	{
		$new_data = new StdClass;
		$mis_data = json_decode($mis_log_detail->mis_data, 1);

		if ($table == 'programme') {
			$fields[] = 'cpl_category_id';
			$fields[] = 'first_time_onair';
		}

		foreach ($fields as $field) {
			$new_data->$field = $mis_data[$table][$field];
		}

		return $new_data;
	}

	private function __updateProgramme($programme_id, $params)
	{
		$programme = new programme;
		$programme_detail = $programme->get($programme_id);
		if (empty($programme_detail)) return FALSE;

		MisCommon::diff($programme_detail, $params, 'programme');

		$programme_detail->modified_at = date('Y-m-d H:i:s');
		$programme_detail->status = AC::STATUS_NEW;
		return $programme->update($programme_detail);
	}

	private function __updateProgrammeLanguage($programme_id, $params, $lang = 'zh')
	{
		switch ($lang) {
			case 'zh':
				$lang_id = language::getLanguageID(AC::LANGUAGE_ZH);
				$type = 'programme-language_zh';
				break;
			case 'en':
				$lang_id = language::getLanguageID(AC::LANGUAGE_EN);
				$type = 'programme-language_en';
				break;
			default:
				return FALSE;
				break;
		}
		
		$programme_language = new programme_language;
		$programme_language_detail = $programme_language->get(array($programme_id, $lang_id));

		MisCommon::diff($programme_language_detail, $params, $type);

		return $programme_language->update($programme_language_detail);
	}

	private function __updateEpisode($episode_id, $new_data, $type) 
	{
		$episode = new episode;
		$episode_detail = $episode->get($episode_id);
		if (empty($episode_detail)) return FALSE;

		MisCommon::diff($episode_detail, $new_data, $type);

    	$episode_detail->status = AC::STATUS_NEW; 
		return $episode->update($episode_detail);
	}
	
	private function __updateEpisodeLanguage($episode_id, $new_data, $type, $lang = 'zh')
	{
		switch ($lang) {
			case 'zh':
				$lang_id = language::getLanguageID(AC::LANGUAGE_ZH);
				break;
			case 'en':
				$lang_id = language::getLanguageID(AC::LANGUAGE_EN);
				break;
			default:
				return FALSE;
				break;
		}
		
		$episode_language = new episode_language;
		$episode_language_detail = $episode_language->get(array($episode_id, $lang_id));
		if (empty($episode_language_detail)) {
			return FALSE;
		}

		MisCommon::diff($episode_language_detail, $new_data, $type);

		return $episode_language->update($episode_language_detail);
	}


	private function __updateCast($cast_id, $new_data)
	{
		$cast = new cast;
		$cast_detail = $cast->get($cast_id);
		if (empty($cast_detail)) return FALSE;

		MisCommon::diff($cast_detail, $new_data, 'Cast');

		$cast_detail->status = AC::STATUS_NEW;
		$cast_detail->modified_at = date('Y-m-d H:i:s');
		return $cast->update($cast_detail);
	}

	private function __updateCastLanguage($cast_id, $new_data, $lang = 'zh')
	{
		switch ($lang) {
			case 'zh':
				$lang_id = language::getLanguageID(AC::LANGUAGE_ZH);
				$type = 'Cast Language';
				break;
			default:
				return FALSE;
				break;
		}

		$cast_language = new cast_language;
		$cast_language_detail = $cast_language->get(array($cast_id, $lang_id));

		MisCommon::diff($cast_language_detail, $new_data, $type);

		return $cast_language->update($cast_language_detail);
	}

	private function __updateInfo($id, $new_data, $type)
	{
		$class = strtolower($type);
		$info = new $class;
		$info_detail = $info->get($id);
		$info_detail->status = AC::STATUS_NEW;
		$info_detail->modified_at = date('Y-m-d H:i:s');

		MisCommon::diff($info_detail, $new_data, $type);

		return $info->update($info_detail);
	}

	private static function __formatInfoAwardData(&$new_data)
	{
		$new_data->winners = CommonUtils::format_field($new_data, 'winners');
		$new_data->nominees = CommonUtils::format_field($new_data, 'nominees');
		$new_data->award_presenters = CommonUtils::format_field($new_data, 'award_presenters');
		$new_data->organizations = CommonUtils::format_field($new_data, 'organizations');
	}

	private static function __formatInfoRecipeData(&$new_data)
	{
		$new_data->designed_by = CommonUtils::format_field($new_data, 'designed_by');
		$new_data->presented_by = CommonUtils::format_field($new_data, 'presented_by');
	}

	private static function __formatInfoSongData(&$new_data)
	{
		$new_data->singers = CommonUtils::format_field($new_data, 'singers');
		$new_data->group_names = CommonUtils::format_field($new_data, 'group_names');
		$new_data->producers = CommonUtils::format_field($new_data, 'producers');
		$new_data->composers = CommonUtils::format_field($new_data, 'composers');
		$new_data->lyricists = CommonUtils::format_field($new_data, 'lyricists');
		$new_data->arrangers = CommonUtils::format_field($new_data, 'arrangers');
	}

	private static function __formatInfoAwardUiData(&$recover_data)
	{
		$recover_data['winners'] = CommonUtils::decode_field((object) $recover_data,'winners');
		$recover_data['award_presenters'] = CommonUtils::decode_field((object) $recover_data,'award_presenters');
		$recover_data['nominees'] = CommonUtils::decode_field((object) $recover_data,'nominees');
		$recover_data['organizations'] = CommonUtils::decode_field((object) $recover_data,'organizations');
	}

	private static function __formatInfoRecipeUiData(&$recover_data)
	{
		$recover_data['designed_by'] = CommonUtils::decode_field((object) $recover_data,'designed_by');
		$recover_data['presented_by'] = CommonUtils::decode_field((object) $recover_data,'presented_by');
	}

	private static function __formatInfoSongUiData(&$recover_data)
	{
		$recover_data['singers'] = CommonUtils::decode_field((object) $recover_data,'singers');
		$recover_data['group_names'] = CommonUtils::decode_field((object) $recover_data,'group_names');
		$recover_data['producers'] = CommonUtils::decode_field((object) $recover_data,'producers');
		$recover_data['composers'] = CommonUtils::decode_field((object) $recover_data,'composers');
		$recover_data['lyricists'] = CommonUtils::decode_field((object) $recover_data,'lyricists');
		$recover_data['arrangers'] = CommonUtils::decode_field((object) $recover_data,'arrangers');
	}

	public function showCasts($json_cast_list)
	{
		$cast_role_list = array();
		$arr_cast = array();
		$cast_role_id = array();

		$crew_role_list = array();
		$crew_role_id = array();
		$arr_crew = array();
		$cast_list = array();
		$crew_list = array();

		$highlighted_cast_roles = CommonUtils::get_highlight_role("programme");

		//cast role list 
		$cast_role = new cast_role();
		if ($highlighted_cast_roles != '') {
			$cast_role_list = $cast_role->findByInSql($highlighted_cast_roles, AC::ROLE_TYPE_CAST);
		}

		foreach ($cast_role_list as $cast) {
			$cast_role_id[] = $cast->id;
			$cast_list[$cast->id] = array();
			$arr_cast[$cast->id] = $cast->system_label;
		}

		//crew role list
		if ($highlighted_cast_roles != '') {
			$crew_role_list = $cast_role->findByInSql($highlighted_cast_roles, AC::ROLE_TYPE_CREW);
		}

		foreach ($crew_role_list as $crew) {
			$crew_role_id[] = $crew->id;
			$crew_list[$crew->id] = array();
			$arr_crew[$crew->id] = $crew->system_label;
		}

		if (!empty($json_cast_list))
		{
			foreach ($json_cast_list as $role_id=>$list)
			{
				if (in_array($role_id, $cast_role_id))
				{
					$cast_list[$role_id] = $list;
				}
				elseif (in_array($role_id, $crew_role_id))
				{
					$crew_list[$role_id] = $list;
				}
			}
		}
		else
		{
			$cast_list = array();
			$crew_list = array();
		}

        $return = '';
        foreach(array('Cast'=>$cast_list,'Crew'=>$crew_list) as $class=>$list){
            if($list){
                $return .= ($return ? "<br />" : '') . '<b>'.$class.'</b><br />';
                foreach($list as $type=>$data){
                    if($data){
                        $name_array = 'arr_'.strtolower($class);
                        $type_array = $$name_array;
                        $return .="&nbsp;<b>{$type_array[$type]}</b><br />";
                        foreach($data as $_cast){
                            $return .= '&nbsp;&nbsp;';
							$name_type = $_cast['name_type'];
							switch($name_type){
							case 1:
							case 2:
								$return .= $this->_format(($name_type==1 ? "Name" : "Cast Name"),14);
								if($_cast['alphabet']){
									$return .= $_cast['last_name'].$_cast['first_name'];
								}else{
									$return .= $_cast['first_name'].' '.$_cast['last_name'];
								}
								break;
							case 11:
							case 12:
								$return .= $this->_format(($name_type==11 ? "Other Name" : "Cast Nickname"),14);
								$return .= $_cast['first_name'];
								break;
							}
                            $return .= ' ';
							if($_cast['cast_id']){
								if(Model::selectBySql("select pdes_id from mis_pdes where type='cast' and pdes_id='{$_cast['cast_id']}'")){
									$return .= "(<a href='http://sit.pdes.tvb.com/pms_detail.html?act=view&pdes_type=cast&id={$_cast['cast_id']}&type=mis'>{$_cast['cast_id']}</a>)";
								}else{
									$return .= "({$_cast['cast_id']})";
								}
							}
							$return .= "<br />";
                        }
						$return .= "<br />";
                    }
                }
            }
        }
        return $return;
	}
	private function _format($s,$l){
		$space = str_repeat('&nbsp;',$l-strlen($s));
		return ($s.':'.$space);
	}
}
?>
